package com.lkl.demo.consumer.listener;

import com.lkl.demo.common.constant.RabbitMQConstant;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
@RabbitListener(queues = RabbitMQConstant.TOPIC_MESSAGE_SMS)
public class SMSHandler {

    @RabbitHandler
    public void smsHandler(Message message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        String res = new String(message.getBody(), StandardCharsets.UTF_8);
        System.out.println("短信处理，接收到了" + res);

//        String s = map.get(RabbitMQConstant.MESSAGE_TYPE);
//        String phone = map.get("phone");
        try {
//            int i = 1 / 0;

            // 调用外部接口，根据不同事件类型，发送不同内容的短信
//            if ("logout".equals(s)) {
//                Thread.sleep(1000);
//                System.out.println("向《" + phone + "》发送了注销成功通知短信");
//            } else if ("regist".equals(s)) {
//                Thread.sleep(1000);
//                System.out.println("向《" + phone + "》发送了注册成功通知短信");
//            }

            // 无异常，确认消息消费成功
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            try {
                //消费者处理出了问题，需要告诉队列信息消费失败
                //true表示消息重新入队列
                channel.basicNack(deliveryTag, false, true);
//                System.err.println("get msg failed msg = " + map);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }
}
